package vip.ifmm.lehouse.user.service.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import vip.ifmm.lehouse.common.bo.SessionBo;
import vip.ifmm.lehouse.common.dto.ServerResponse;
import vip.ifmm.lehouse.common.enums.status.UserLoginStatus;
import vip.ifmm.lehouse.common.model.User;
import vip.ifmm.lehouse.common.util.CodeUtil;
import vip.ifmm.lehouse.common.util.Md5Util;
import vip.ifmm.lehouse.user.service.api.UserLoginService;
import vip.ifmm.lehouse.user.service.dao.UserLoginDao;
import vip.ifmm.lehouse.user.service.utils.RedisUtil;
import vip.ifmm.lehouse.user.service.utils.SessionUtil;

import javax.annotation.Resource;

/**
 * 用户登录实现类
 *
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/16 16:38
 */

@Service(owner = "red",
         mock = "vip.ifmm.lehouse.user.service.api.mock.UserLoginServiceMock")
public class UserLoginServiceImpl implements UserLoginService {

    // 登录dao
    @Resource
    private UserLoginDao loginDao;

    // 用户登录
    @Override
    public ServerResponse<String> login(User user) {

        // 用户名或密码为空
        if(user == null || (user.getUserNickname() == null && user.getUserEmail() == null) ||
            user.getUserPassword() == null) {
            return ServerResponse.response(UserLoginStatus.USER_IS_EMPTY);
        }
        // 判断用户是否存在
        User userInDB = getUserByUserNameOrEmail(user);
        if(userInDB == null) {
            return ServerResponse.response(UserLoginStatus.USER_NOT_EXISTED);
        }
        // 得到二次加密的密码
        String md5PassWord = Md5Util.DoubleMD5(user.getUserPassword());
        // 校验密码的正确性
        if(!md5PassWord.equals(userInDB.getUserPassword())) {
            return ServerResponse.response(UserLoginStatus.PASSWORD_USERNAME_NOT_RIGHT);
        }
        // 登录逻辑成功，将session放入redis，key为token
        // 响应的数据为token
        return ServerResponse.response(UserLoginStatus.LOGIN_SUCCESS,
                SessionUtil.putSession(SessionUtil.getSessionBo(userInDB)));
    }

    // 从redis中获得session
    @Override
    public ServerResponse<SessionBo> getSessionByToken(String token) {
        // 如果token是空
        if(CodeUtil.isBlank(token)) {
            return ServerResponse.response(UserLoginStatus.TOKEN_IS_NULL);
        }
        return ServerResponse.response(UserLoginStatus.GET_SESSION_SUCCESS,
                RedisUtil.get(token, SessionBo.class));
    }

    // 根据用户名或者邮箱去查找用户
    private User getUserByUserNameOrEmail(User user) {
        // 邮箱或者用户名至少一个不为空
        if(user.getUserEmail() != null || user.getUserNickname() != null) {
            return loginDao.getUserByUserNameOrEmail(user);
        } else {
            return null;
        }
    }

}
